package com.pda.yuanjing.pages.sytj;

import android.app.DatePickerDialog;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.pda.yuanjing.PDApp;
import com.pda.yuanjing.R;
import com.pda.yuanjing.beanin.JieDianBeanIn;
import com.pda.yuanjing.beanout.JDBeanNewOut;
import com.pda.yuanjing.beanout.PPBeanOut;
import com.pda.yuanjing.beanout.SCBeanOut;
import com.pda.yuanjing.beanout.TJBeanOut;
import com.pda.yuanjing.boardcast.CustomReceiver;
import com.pda.yuanjing.boardcast.ScannerInterface;
import com.pda.yuanjing.dialog.product.ProductAllDialog;
import com.pda.yuanjing.dialog.product.ProductDialog;
import com.public_module.basemvp.activity.BaseActivity;
import com.public_module.config.ApiYJ;
import com.public_module.config.SetConfig;
import com.public_module.tools.DateUtils;
import com.public_module.tools.SharedPreferencesManger;
import com.public_module.tools.StringProcess;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;

public class TJActivity extends BaseActivity<PageModel, PageView, PagePresent> implements PageView {
    @BindView(R.id.iv_title_left)
    ImageView ivTitleLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rltitle)
    RelativeLayout rltitle;
    @BindView(R.id.listView)
    ListView listView;
    @BindView(R.id.tvr)
    TextView tvr;
    @BindView(R.id.tvb)
    TextView tvb;
    @BindView(R.id.tve)
    TextView tve;
    @BindView(R.id.tvsc)
    TextView tvsc;
    @BindView(R.id.tvcp)
    TextView tvcp;
    @BindView(R.id.tvkf)
    TextView tvkf;
    @BindView(R.id.logine)
    Button logine;

    private String TAG = "TJActivity";
    ItemAdapter itemAdapter;
    ScannerInterface scanner;
    CustomReceiver customReceiver = null;
    private OptionsPickerView pickerView;
    ProductAllDialog productDialog;
    String pid = "-1";
    String pname = "";
    String pstr = "-1";
    long bt = 0;
    long et = 0;
    JDBeanNewOut.DataBean dataBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tj);
        ButterKnife.bind(this);
        tvTitle.setText("溯源统计 " + SharedPreferencesManger.getRealName());
        scanner = new ScannerInterface(this);
        scanner.setOutputMode(1);
        customReceiver = new CustomReceiver(
                new CustomReceiver.PListener1() {
                    @Override
                    public void setData(CustomReceiver.Dataa dataa) {
                    }
                },
                new CustomReceiver.PListener2() {
                    @Override
                    public void setText(String string) {
                        String ss = StringProcess.codeMat(string);
                        if (!PDApp.scanfp) {
                            getRes("1", ss);
                            return;
                        }
                        if (!PDApp.scanfs) {
                            getRes("2", ss);
                            return;
                        }
                    }
                });
        IntentFilter filter = new IntentFilter();
        filter.addAction(ScannerInterface.RES_ACTION);
        registerReceiver(customReceiver, filter);
        dataBean = (JDBeanNewOut.DataBean)getIntent().getSerializableExtra(PDApp.process);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (customReceiver != null) {
            unregisterReceiver(customReceiver);
        }
        if (scanner != null) {
            scanner.setOutputMode(0);
        }
    }

    @Override
    public PageModel createModel() {
        return new PageModelImpl(this);
    }

    @Override
    public PageView createView() {
        return this;
    }

    @Override
    public PagePresent createPresenter() {
        return new PagePresent();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void tip(String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showMsg(str);
            }
        });
    }

    @Override
    public void tipS(TJBeanOut tjBeanOut) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                itemAdapter = new ItemAdapter(TJActivity.this, tjBeanOut.getData());
                listView.setAdapter(itemAdapter);
            }
        });
    }

    @OnClick({R.id.iv_title_left, R.id.tvcp  , R.id.tvsc   , R.id.tvb  , R.id.tve  , R.id.logine})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
            case R.id.logine:
                if(bt>et){
                    showMsg("结束时间必须大于开始时间");
                    return;
                }
                presenter.query(tvb.getText().toString(),tve.getText().toString(),pstr,pid,pname);
                break;
            case R.id.tvb:
                Calendar calendar=Calendar.getInstance();
                DatePickerDialog dialog=new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        String desc=String.format("%d-%02d-%02d",year,month+1,dayOfMonth);
                        tvb.setText(desc);
                        bt = DateUtils.timeToStamp(desc);
                    }
                },
                        calendar.get(Calendar.YEAR),
                        calendar.get(Calendar.MONTH),
                        calendar.get(Calendar.DAY_OF_MONTH));
                     dialog.show();
                break;
            case R.id.tve:
                Calendar calendar1=Calendar.getInstance();
                DatePickerDialog dialog1=new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        String desc=String.format("%d-%02d-%02d",year,month+1,dayOfMonth);
                        tve.setText(desc);
                        et = DateUtils.timeToStamp(desc);
                    }
                },
                        calendar1.get(Calendar.YEAR),
                        calendar1.get(Calendar.MONTH),
                        calendar1.get(Calendar.DAY_OF_MONTH));
                dialog1.show();
                break;
            case R.id.tvsc:
                List<PPBeanOut.DataBean> options1Items = new ArrayList<>();
                List<List<String>> options2Items = new ArrayList<>();
                List<PPBeanOut.DataBean> listt = new ArrayList<>();
                PPBeanOut.DataBean temp = new PPBeanOut.DataBean();
                temp.setProcessID("-1");
                temp.setProcessName("全部流程");
                List<String> lists = new ArrayList<>();
                lists.add("全部工艺");
                temp.setListJieDianName(lists);
                listt.add(temp);
                listt.addAll(PDApp.ppBeanOut.getData());
                for (int i = 0; i < listt.size(); i++) {
                    PPBeanOut.DataBean pt = listt.get(i);
                    options1Items.add(pt);
                    List<String> ptl = new ArrayList<>();
                    for (int j = 0; j < listt.get(i).getListJieDianName().size(); j++) {
                        ptl.add(listt.get(i).getListJieDianName().get(j));
                    }
                    options2Items.add(ptl);
                }

                for (int i = 0; i < listt.size(); i++) {
                    PPBeanOut.DataBean pt = listt.get(i);
                    options1Items.add(pt);
                    List<String> ptl = new ArrayList<>();
                    for (int j = 0; j < listt.get(i).getListJieDianName().size(); j++) {
                        ptl.add(listt.get(i).getListJieDianName().get(j));
                    }
                    options2Items.add(ptl);
                }
                pickerView = new OptionsPickerBuilder(TJActivity.this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        String tx = options1Items.get(options1).getPickerViewText() + "-"
                                + options2Items.get(options1).get(options2);
                        pid = options1Items.get(options1).getProcessID();
                        pname = options2Items.get(options1).get(options2);
                        tvsc.setText(tx);
                    }
                })
                        .setTitleText("选择生产流程")
                        .setContentTextSize(20)//设置滚轮文字大小
                        .setTitleSize(20)
                        .setSubCalSize(20)
                        .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                        .setSelectOptions(0)//默认选中项
                        .setBgColor(Color.WHITE)
                        .setTitleBgColor(getResources().getColor(R.color.white))
                        .setTitleColor(getResources().getColor(R.color.black))
                        .setCancelColor(getResources().getColor(R.color.gray_high))
                        .setSubmitColor(getResources().getColor(R.color.blue))
                        .setTextColorCenter(getResources().getColor(R.color.black))
                        .setSubmitText("确定")
                        .setCancelText("取消")
                        .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                        .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                        .setOutSideColor(0x2A2A2A4F) //设置外部遮罩颜色
                        .build();
                pickerView.setPicker(options1Items, options2Items);
                pickerView.show();
                break;
            case R.id.tvcp:
                tvcp.setEnabled(false);
                presenter.initBase(pid,pname);
                productDialog = new ProductAllDialog(mContext, R.style.CommentDialog, new ProductAllDialog.PriorityListener() {
                    @Override
                    public void setActivityText(String str, String str1,int num) {
                        tvcp.setText(str);
                        pstr = str1;
                        productDialog.dismiss();
                    }
                });
                WindowManager.LayoutParams lp = productDialog.getWindow().getAttributes();
                lp.gravity = Gravity.CENTER;
                productDialog.show();
                tvcp.setEnabled(true);
                break;
        }
    }

    public void getRes(String id, String code) {
        try {
            showProgress();
            Gson gson = new Gson();
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(SetConfig.getConnectTimeout(), TimeUnit.SECONDS)
                    .readTimeout(SetConfig.getReadTimeout(), TimeUnit.SECONDS)
                    .writeTimeout(SetConfig.getWriteTimeout(), TimeUnit.SECONDS)
                    .followRedirects(false)
                    .build();
            ApiYJ apisync = new Retrofit.Builder()
                    .baseUrl("http://" + SharedPreferencesManger.getHostName() + "/")
                    .client(client)
                    .build().create(ApiYJ.class);

            JieDianBeanIn jieDianBeanIn = new JieDianBeanIn();
            jieDianBeanIn.setAction("SY_QueryProdcutStoreByCode");
            jieDianBeanIn.setCid(SharedPreferencesManger.getCid());
            jieDianBeanIn.setUserID(SharedPreferencesManger.getUid());
            jieDianBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            jieDianBeanIn.setBaseType(id);
            jieDianBeanIn.setCodecc(code);
            jieDianBeanIn.setProcessID(Integer.parseInt(pid));

            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(jieDianBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            LogUtils.e(StringProcess.responsetoString(response.body()));
                            SCBeanOut scBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), SCBeanOut.class);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (id.equals("1")) {
                                        productDialog.dismiss();
                                        if (scBeanOut.getData().getIdStr().equals("-1")) {
                                            showMsg("未匹配到产品信息");
                                        } else {
                                            boolean flag = true;
                                            for (int i = 0; i <PDApp.productBeanOutt.getData().size() ; i++) {
                                                if(PDApp.productBeanOutt.getData().get(i).getId().equals(scBeanOut.getData().getIdStr())){
                                                    flag = false;
                                                    break;
                                                }
                                            }
                                            if(flag){
                                                showMsg("未匹配到产品信息");
                                                return;
                                            }
                                            tvcp.setText(scBeanOut.getData().getNameStr());
                                            pstr = scBeanOut.getData().getIdStr();
                                        }
                                    } else if (id.equals("2")) {
                                        if (scBeanOut.getData().getIdStr().equals("-1")) {
                                            showMsg("未匹配到库房信息");
                                        } else {
                                            boolean flag = true;
                                            for (int i = 0; i <PDApp.storeBeanOutt.getData().size() ; i++) {
                                                if(PDApp.storeBeanOutt.getData().get(i).getId().equals(scBeanOut.getData().getIdStr())){
                                                    flag = false;
                                                    break;
                                                }
                                            }
                                            if(flag){
                                                showMsg("未匹配到库房信息");
                                                return;
                                            }
                                        }
                                    }
                                }
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                    }
                }
            });
            thread.start();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            hideProgress();
            return;
        }
    }
}
